addLoadEvent(prepareGallery());
addLoadEvent(preparePlaceholder());

function showPic(whichpic) {
    var source = whichpic.getAttribute("href");
    var placeHolder = document.getElementById("placeholder");
    var text = whichpic.getAttribute("title");
    var description = document.getElementById("description");
    description.firstChild.nodeValue = text;
    placeHolder.setAttribute("src", source);
}

function prepareGallery(){
    var gallery = document.getElementById("gallery");
    var links = gallery.getElementsByTagName("a");
    for(var i = 0; i < links.length; i++){
        links[i].onclick = function () {
            showPic(this);
            return false;
        }
    }
}

function preparePlaceholder() {
    var placeholder = document.createElement("img");
    placeholder.setAttribute("src", "images/1.jpg");
    placeholder.setAttribute("alt", "image gallery");
    placeholder.setAttribute("id", "placeholder");
    var desc = document.createElement("p");
    desc.setAttribute("id","description");
    var desctext = document.createTextNode("Choose an image");
    desc.appendChild(desctext);
    var gallery = document.getElementById("gallery");
    insertAfter(desc, gallery);
    insertAfter(placeholder, gallery);
}



/*
    在节点后插入节点
 */
function insertAfter(newElement, targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild === targetElement) {
        parent.appendChild(newElement);
    } else {
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

/**
 * 添加onload事件
 * @param func
 */
function addLoadEvent(func) {
    var oldload = window.onload;
    if (typeof oldload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldload();
            func();
        }
    }
}